﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using IndignadoFramework.BackBone.Model;
using Argotic.Common;
using Argotic.Syndication;

namespace SimpleRssReader.Services
{
    public class RssReaderService : IRssReaderService
    {
        public RssReaderService()
        {
        }

        public RSSFeedContentModel ReadFeed(List<string> feedUrl, int numberOfItems)
        {
            RSSFeedContentModel datos = new RSSFeedContentModel();

            foreach (string url in feedUrl)
            {

                var settings = new SyndicationResourceLoadSettings
                {
                    RetrievalLimit = numberOfItems
                };

                var feed = GenericSyndicationFeed.Create(new Uri(url), settings);

                if (feed.Resource is RssFeed)
                {
                    datos = ReadRssFeed((RssFeed)feed.Resource);
                }

                if (feed.Resource is AtomFeed)
                {
                    datos = ReadAtomFeed((AtomFeed)feed.Resource);
                }

                //throw new InvalidOperationException("Feed has unsupported format");
            }
            return datos;
        }

        private RSSFeedContentModel ReadRssFeed(RssFeed feed)
        {
            var rssContentModel = new RSSFeedContentModel
            {
                FeedTitle = feed.Channel.Title,
                Articles = feed.Channel.Items.Select(item => new RSSArticleModel
                {
                    Title = item.Title,
                    Content = item.Description,
                    PublicationDate = item.PublicationDate,
                    Link = item.Link,
                    Author = item.Author
                })
            };

            return rssContentModel;
        }

        private RSSFeedContentModel ReadAtomFeed(AtomFeed feed)
        {
            var rssContentModel = new RSSFeedContentModel
            {
                FeedTitle = feed.Title.Content,
                Articles = feed.Entries.Select(item => new RSSArticleModel
                {
                    Title = item.Title.Content,
                    Content = item.Content.Content,
                    PublicationDate = item.PublishedOn,
                    Link = item.Links.FirstOrDefault().Uri,
                    Author = string.Join(", ", item.Authors.Select(a => a.Name))
                })
            };

            return rssContentModel;
        }
    }
}